package com.java46.gougoussowebs.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gougou.common.util.CookieUtils;
import com.gougou.common.util.GetData;

import com.gougou.redis.service.RedisService;
import com.gougou.sso.pojo.TbUser;
import com.gougou.sso.service.MPTbUserService;
import com.java46.gougoussowebs.service.NoteService;
import com.java46.gougoussowebs.util.Encryption;
import com.java46.gougoussowebs.util.MailSenderInfo;
import com.java46.gougoussowebs.util.RandomNote;
import com.java46.gougoussowebs.util.SimpMailSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2018-09-07
 */
@Controller
@RequestMapping("/tbUser")
@CrossOrigin
public class TbUserController {

    @Autowired
    private MPTbUserService mpTbUserService;
    @Autowired
    private NoteService noteService;
    @Autowired
    private RedisService redisService;

    private static final ObjectMapper objmapper = new ObjectMapper();
    private static final Integer REDIS_TIME = 60 * 30;
    private static final String COOKIE_NAME = "TT_TOKEN";
    private static final String RANDOM = "radom";
    private static HashMap<Object,Object> hashMap =new HashMap<Object, Object>();

    /***************************************************
     * 检测数据的有效性
     * @param parm
     * @param type
     * @return
     * *************************************************
     */
    @RequestMapping("/check/{parm}/{type}")
    @ResponseBody
    public boolean checkUser(@PathVariable String parm, @PathVariable Integer type) {
        EntityWrapper<TbUser> tbUserEntityWrapper = new EntityWrapper<TbUser>();
        //判断需要检测的类容
        switch (type) {
            case 1:
                tbUserEntityWrapper.where("username={0}", parm);
                break;
            case 2:
                tbUserEntityWrapper.where("phone={0}", parm);
                break;
            case 3:
                tbUserEntityWrapper.where("email={0}", parm);
                break;
            default:
                break;
        }
        try {
            TbUser tbUser = mpTbUserService.selectOne(tbUserEntityWrapper);
            if (tbUser == null) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

    /********************************************************
     * 添加用户
     * @param tbUser
     * @return
     * ******************************************************
     */
    @RequestMapping("/add")
    @ResponseBody
    public HashMap<Object, Object> addUser(@Valid TbUser tbUser , String mobileCode , BindingResult bindingResult) {

        HashMap<Object, Object> objectObjectHashMap = new HashMap<Object, Object>();
        if(bindingResult.hasErrors()){
            //没有通过矫正
            objectObjectHashMap.put("status","400");
            objectObjectHashMap.put("data","参数有误");
            return objectObjectHashMap;
        }
        //从redis里面取出验证码
//        System.out.println(RANDOM + Encryption.encryptionMd5(tbUser.getPhone()));
        try{
            String s1 = redisService.get(RANDOM + Encryption.encryptionMd5(tbUser.getPhone()));
            if(s1==null){
                objectObjectHashMap.put("status", "400");
                objectObjectHashMap.put("data","验证码无效");
                return objectObjectHashMap;
            }
            if(mobileCode =="" || Integer.parseInt(mobileCode) != Integer.parseInt(s1)){
                objectObjectHashMap.put("status", "400");
                objectObjectHashMap.put("data","验证码为空,请输入验证码");
                return objectObjectHashMap;
            }
            //初始化时间
            tbUser.setCreated(GetData.getDate());
            tbUser.setUpdated(GetData.getDate());
            //取出密码
            String pwd = tbUser.getPassword();
            //把密码进行MD5加密
            String s = Encryption.encryptionMd5(pwd);
            //把加密后的密码放回去
            tbUser.setPassword(s);
            //添加用户
            boolean insert = mpTbUserService.insert(tbUser);
            if (!insert) {
                objectObjectHashMap.put("status", "400");
                return objectObjectHashMap;
            }
            objectObjectHashMap.put("status", "200");
            return objectObjectHashMap;
        }catch (Exception e){
            e.printStackTrace();
            objectObjectHashMap.put("data","系统错误");
            objectObjectHashMap.put("status", "400");
            return objectObjectHashMap;
        }

    }

    /********************************************
     * 用户登录
     * @param username
     * @param password
     * @return
     * *******************************************
     */
    @RequestMapping("/login")
    @ResponseBody
    public HashMap<Object, Object> loginUser(String username, String password , HttpServletRequest resques, HttpServletResponse respon) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<Object, Object>();
        //密码进行加密
        String s = Encryption.encryptionMd5(password);
        EntityWrapper<TbUser> tbUserEntityWrapper = new EntityWrapper<TbUser>();
        tbUserEntityWrapper.where("username={0} and password={1}", username, s);
        TbUser tbUser = mpTbUserService.selectOne(tbUserEntityWrapper);
        if (tbUser == null) {
            //登录失败
            objectObjectHashMap.put("status", "500");
            return objectObjectHashMap;
        }
        //创建一个key键
        String token = Encryption.encryptionMd5(username + System.currentTimeMillis());
        try {
            //执行Redis保存操作
            redisService.set("TOKEN_" + token, objmapper.writeValueAsString(tbUser), REDIS_TIME);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            //登录失败
            objectObjectHashMap.put("status", 500);
        }
        //登录成功
        objectObjectHashMap.put("status", 200);
        CookieUtils.setCookie(resques,respon,COOKIE_NAME,token);
        return objectObjectHashMap;
    }

    /********************************************
     * 检测邮箱是否被使用
     * @param email
     * @return
     * *******************************************
     */
    @RequestMapping("/emailcheck")
    @ResponseBody
    public HashMap<Object, Object> Emailcheck(String email) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<Object, Object>();
        EntityWrapper<TbUser> objectEntityWrapper = new EntityWrapper<TbUser>();
        objectEntityWrapper.where("email={0}", email);
        try {
            TbUser tbUser = mpTbUserService.selectOne(objectEntityWrapper);
            if (tbUser == null) {
                objectObjectHashMap.put("success", "0");
                return objectObjectHashMap;
            } else {
                objectObjectHashMap.put("success", "1");
                return objectObjectHashMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            objectObjectHashMap.put("success", 2);
            return objectObjectHashMap;
        }
    }

    /*****************************************
     * 检测手机是否存在
     * @param mobile
     * @return
     * ***************************************
     */
    @RequestMapping("/phone")
    @ResponseBody
    public HashMap<Object, Object> mobile(String mobile) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<Object, Object>();
        EntityWrapper<TbUser> objectEntityWrapper = new EntityWrapper<TbUser>();
        objectEntityWrapper.where("phone={0}", mobile);
        try {
            TbUser tbUser = mpTbUserService.selectOne(objectEntityWrapper);
            if (tbUser == null) {
                objectObjectHashMap.put("success", "0");
                return objectObjectHashMap;
            } else {
                objectObjectHashMap.put("success", "1");
                return objectObjectHashMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            objectObjectHashMap.put("success", 2);
            return objectObjectHashMap;
        }
    }

    /**************************************************
     * 发送短信
     * @param mobile
     * @param state
     * @return
     * ************************************************
     */
    @RequestMapping("/notSend")
    @ResponseBody
    public HashMap<Object, Object> noteSend(String mobile, String state) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<Object, Object>();

        //判断state是否为空
        if (state == null || "".equals(state)) {
            objectObjectHashMap.put("remain", "true");
        } else {
            objectObjectHashMap.put("remain", "false");
        }

        //判断手机号是否被使用
        HashMap<Object, Object> mobiale1 = this.mobile(mobile);
        Object success = mobiale1.get("success");
        if (Integer.parseInt(String.valueOf(success)) == 1) {
            objectObjectHashMap.put("info", "true");
            return objectObjectHashMap;
        }
        //手机号进行md5加密
        String s = Encryption.encryptionMd5(mobile);
        //生成一个随机数
        Integer rum = Integer.parseInt(RandomNote.random());
//        System.out.println(RANDOM+s);
        //验证码存入redis里面去
        redisService.set(RANDOM+s,rum.toString(),120);
        try {
            //发送短信
            boolean note = noteService.note(mobile, rum.toString());
            if (note) {
                objectObjectHashMap.put("rs", "1");
                objectObjectHashMap.put("remain", "发送成功");
                return objectObjectHashMap;
            } else {
                objectObjectHashMap.put("rs", "-2");
                return objectObjectHashMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            objectObjectHashMap.put("rs", -1);
            return objectObjectHashMap;
        }
    }

    /*********************************************
     * 发送邮件
     * @param tbUser
     * *******************************************
     */

    @RequestMapping("/sendRegEmail")
    @ResponseBody
    public HashMap<Object, Object> sendRegEmail(TbUser tbUser,String verificationCode) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<Object, Object>();
        //从redis里取出验证码
        String s = redisService.get(RANDOM + Encryption.encryptionMd5(tbUser.getPhone()));
        //判断验证码是否正确
//        try{
//            if(Integer.parseInt(verificationCode)!=Integer.parseInt(s) || verificationCode==null){
//                objectObjectHashMap.put("success","1");
//                objectObjectHashMap.put("info","验证码输入错误或验证码无效");
//                return objectObjectHashMap;
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            objectObjectHashMap.put("success","1");
//            objectObjectHashMap.put("info","验证码输入错误或验证码无效");
//            return objectObjectHashMap;
//        }

        //邮件发送
        try {
            MailSenderInfo mailSenderInfo = new MailSenderInfo();//邮件信息类
            mailSenderInfo.setMailServerHost("smtp.qq.com");//发送邮件的主机
            mailSenderInfo.setMailServerPort("25");//发送邮件的端口号

            mailSenderInfo.setUserName("2645740054");//发送邮件的账号
            mailSenderInfo.setPassword("uhahkiaodhleecjc");//发送邮件的密码（注意：密码是该邮箱的授权码）
            mailSenderInfo.setFromAdress("2645740054@qq.com");//发送邮箱的地址

            mailSenderInfo.setToAdress(tbUser.getEmail());
            mailSenderInfo.setSubject("登录够够商城验证邮箱");
            String s1 = Encryption.encryptionMd5(tbUser.getEmail());
            //将用户信息存入redis里面去
            hashMap.put(s1,tbUser);
            mailSenderInfo.setContent("<span style=\"font-family:arial;font-size:12px;color:red\">" +
                    "<a href=\"http://sso.taotaoo.xyz/tbUser/emailUserAdd?email="+tbUser.getEmail()+"&date="+GetData.getDate()+"\">" +
                    "点击验证</a></span>");

            SimpMailSender simpMailSender=new SimpMailSender();
            simpMailSender.sendeHtmlMail(mailSenderInfo);
            objectObjectHashMap.put("success","0");
            objectObjectHashMap.put("k","发送成功");
            return objectObjectHashMap;
        }catch (Exception e){
            e.printStackTrace();
            objectObjectHashMap.put("info","系统出错，程序员正在吃泡面！！！！！");
            objectObjectHashMap.put("success","1");
            return objectObjectHashMap;
        }
    }
    /********************************************************
     * 邮箱验证成功后添加用户
     * @param email
     * @return
     * ******************************************************
     */
    @RequestMapping("/emailUserAdd")
    public String emailUserAdd(String email,String date) {
        String s1 = Encryption.encryptionMd5(email);

        Date dates=new Date(date);
        Date date1 =new Date(String.valueOf(GetData.getDate()));

        int i = (int) ( date1.getTime()- dates.getTime());
        //判断邮件的有效期
        if(i>60000){
            return "shixiao";
        }
        if(hashMap.get(s1)==null){
            return "shixiao";
        }
        //获取tbuser对象
        TbUser tbUsers = (TbUser) hashMap.get(s1);
        hashMap.remove(s1);
        Object o = hashMap.get(s1);
        //初始化时间
        tbUsers.setCreated(GetData.getDate());
        tbUsers.setUpdated(GetData.getDate());
        try {
            //取出密码
            String pwd = tbUsers.getPassword();
            //把密码进行MD5加密
            String s = Encryption.encryptionMd5(pwd);
            //把加密后的密码放回去
            tbUsers.setPassword(s);
            //添加用户
            boolean insert = mpTbUserService.insert(tbUsers);
            if (!insert) {
                return "my-exception";
            }
            return "exception";
        } catch (Exception e) {
            e.printStackTrace();
            return "my-exception";
        }
    }

}


